package com.treasure.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.treasure.common.types.Corp;
import com.treasure.common.utils.RandomIdGenerator;
import com.treasure.infrastructure.model.po.CorpAccessToken;
import com.treasure.infrastructure.model.po.CorpInfo;
import com.treasure.infrastructure.repository.dao.mapper.CorpAccessTokenMapper;
import com.treasure.infrastructure.repository.dao.mapper.CorpInfoMapper;
import com.treasure.web.command.response.CorpAccountTokenResponse;
import com.treasure.web.mapstruct.CorpAccountTokenInfoAssembler;
import com.treasure.web.service.ICorpAccessTokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.treasure.web.service.ICorpInfoService;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sunhongmin
 * @since 2023-11-11
 */
@Service
public class CorpAccessTokenServiceImpl extends ServiceImpl<CorpAccessTokenMapper, CorpAccessToken> implements ICorpAccessTokenService {
    @Resource
    CorpInfoMapper corpInfoMapper;
    @Resource
    ICorpInfoService corpInfoService;

    @Override
    public CorpAccountTokenResponse getCorpAccountTokenInfo(Corp corp) {
        QueryWrapper<CorpAccessToken> corpAccountTokenQuery = new QueryWrapper<>();
        corpAccountTokenQuery.lambda().eq(CorpAccessToken::getCorpId, corp.getValue());
        CorpAccessToken corpAccountTokenInfo = getOne(corpAccountTokenQuery);

        if (Objects.isNull(corpAccountTokenInfo)) {
            CorpInfo corpInfo = corpInfoService.getEffectiveCorpInfo(corp);
            // 新建授权信息
            CorpAccessToken corpAccessToken = getCorpAccessToken(corp, corpInfo);
            save(corpAccessToken);
            return CorpAccountTokenInfoAssembler.INSTANCE.convertToResponse(corpAccessToken);
        }


        return CorpAccountTokenInfoAssembler.INSTANCE.convertToResponse(corpAccountTokenInfo);
    }

    @NotNull
    private static CorpAccessToken getCorpAccessToken(Corp corp, CorpInfo corpInfo) {
        CorpAccessToken corpAccessToken = new CorpAccessToken();
        corpAccessToken.setCorpId(corp.getValue());
        corpAccessToken.setAppKey(corpInfo.getInviteCode());
        corpAccessToken.setAccessToken(RandomIdGenerator.accountToken());
        corpAccessToken.setAuthorizationStatus(1);
        LocalDateTime now = LocalDateTime.now();
        corpAccessToken.setExpireDate(now.plusYears(2));
        corpAccessToken.setCreateTime(now);
        corpAccessToken.setIpWhitelist("0.0.0.0");
        return corpAccessToken;
    }
}
